package com.itheima.reflect;

import com.itheima.junit.StringUtil;
import org.junit.Test;

import javax.xml.transform.Source;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
* 获取构造器
* */

public class Test2Constructor {

    @Test
    public void testGetConstructors(){
        Class c1=Student.class; //获取Class对象
        //只能获取public修饰的构造器
        Constructor[] constructors = c1.getConstructors();
        for(Constructor constructor:constructors){
            System.out.println(constructor);
            //对象全路径   对象参数
            System.out.println(constructor.getName()+"---"+constructor.getParameterCount());
        }

        System.out.println("---------------------");

        //获取所有构造器
        Constructor[] constructors2 = c1.getDeclaredConstructors();
        for(Constructor constructor:constructors2){
            System.out.println(constructor);
            //对象全路径   对象参数
            System.out.println(constructor.getName()+"---"+constructor.getParameterCount());
        }
    }

    @Test
    public void testGetConstructor() throws Exception{
        Class c1=Student.class;

        //只能获取public修饰的无参数构造器
        Constructor constructor = c1.getConstructor();
        System.out.println(constructor);

        //能获取所有的无参数构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor();
        System.out.println(declaredConstructor);

        declaredConstructor.setAccessible(true);    //静止检查访问权限
        Student s1= (Student)declaredConstructor.newInstance(); //实例化对象
        System.out.println(s1);

        //获取有参数的构造器
        Constructor declaredConstructor1 = c1.getDeclaredConstructor(Integer.class, String.class);
        System.out.println(declaredConstructor1);
        declaredConstructor1.setAccessible(true);   //静止检查访问权限
        Student s2=(Student) declaredConstructor1.newInstance(1,"hover");
        System.out.println(s2);
    }

}
